package com.controller;

import com.beans.CategoryEntity;
import com.beans.ErrorStatusEnum;
import com.common.entity.R;
import com.repository.CategoryRepository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * @author gm
 * @description 设备类型CRUD
 * @date 2020/5/29
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("category")
public class CategoryController {

    @PersistenceContext
    private EntityManager entityManager;
    @Resource
    private CategoryRepository categoryRepository;

    /**
     * 获取所有设备类型
     * 无参查全部，参数为1查询已启用的类型
     *
     * @param state 状态
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/29
     */
    @GetMapping("getCategory")
    public R getCategory(Integer state) {
        List result = getCategoryListByParentId(0, state);
        String sql = " select count(id) from category where 1=1 ";
        if (state != null) {
            sql += " and state = " + state;
        }
        Object total = entityManager.createNativeQuery(sql).getSingleResult();
        R ok = R.ok();
        ok.put("rows", result);
        ok.put("total", total);
        return ok;
    }

    /**
     * 添加和修改设备类别，包括子节点的修改，添加
     *
     * @param category 类别实体
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/30
     * 修改事件：2020/6/7 wyj
     */

    @PostMapping("mergeCategory")
    public R createCategory(@Valid CategoryEntity category) {
        category.setCreateTime(new Date());
        category = entityManager.merge(category);
        return R.ok(category);
    }


    /**
     * 删除设备类别
     *
     * @param ids json格式的ids [1,2,3]
     * @return com.common.entity.R
     * @author gm
     * @date 2020/5/30
     */
    @PostMapping("deleteCategory")
    public R deleteCategory(@RequestParam(value = "ids[]") List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return R.error(ErrorStatusEnum.PARAMS_CANNOT_BE_NULL_ERROR.code(), "删除操作，id不能为空!");
        }
        entityManager.createNativeQuery("update category set state = 0 where id in :id").setParameter("id", ids).executeUpdate();
        return R.ok();
    }

    /**
     * 根据父菜单id查询所有子菜单
     */
    private List getCategoryListByParentId(Integer parentId, Integer state) {
        String hql = " from CategoryEntity where parentId = :parentId ";
        if (state != null) {
            hql += " and state = " + state;
        }
        List<CategoryEntity> resultList = entityManager.createQuery(hql, CategoryEntity.class).setParameter("parentId", parentId).getResultList();
        if (!CollectionUtils.isEmpty(resultList)) {
            for (CategoryEntity category : resultList) {
                List categoryList = getCategoryListByParentId(category.getId(), state);
                if (!CollectionUtils.isEmpty(categoryList)) {
                    category.setChildren(categoryList);
                }
            }
        }
        return resultList;
    }

}
